﻿using Identity.API.Data;
using Identity.API.Models;
using Microsoft.EntityFrameworkCore;
using RepositoryLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Identity.API.Services
{
    public class UserLogRepository : IUserLogRepository
    {
        private readonly ApplicationDbContext _context;
        public IUnitOfWork UnitOfWork
        {
            get
            {
                return _context;
            }
        }

        public UserLogRepository(ApplicationDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public WeChatLoginUserLog Add(WeChatLoginUserLog userLog)
        {
            if (userLog.IsTransient())
            {
                return _context.WeChatLoginUserLogs
                    .Add(userLog)
                    .Entity;
            }
            else
            {
                return userLog;
            }
        }

        public WeChatLoginUserLog Update(WeChatLoginUserLog userLog)
        {
            return _context.WeChatLoginUserLogs
                    .Update(userLog)
                    .Entity;
        }

        public async Task<WeChatLoginUserLog> FindByIdAsync(string id)
        {
            var userLog = await _context.WeChatLoginUserLogs
                .Where(b => b.Id == int.Parse(id))
                .FirstOrDefaultAsync();
            return userLog;
        }

        public async Task<WeChatLoginUserLog> FindByGuidAsync(string guid)
        {
            var userLog = await _context.WeChatLoginUserLogs
                .Where(b => b.LoginGuid == guid)
                .FirstOrDefaultAsync();
            return userLog;
        }
    }
}
